/**
 * 获取cookie中的user，并验证是否存在这个用户
 * @function decodeUser
 * @param ctx
 * @param next
 * @returns {string}
 */
const jwt = require('jsonwebtoken');

module.exports = options => {
    return async (ctx, next) => {
        let user = ctx.cookies.get('user');
        // console.log('decodeUser 1', user);
        if (user) {
            user = jwt.verify(user, ctx.app.config.jwtKey);
            if (user && user.id) {
                user = await ctx.app.model.User.findOne({
                    where: {id: user.id},
                    include: [{model: ctx.app.model.UserLevel, as: 'level'}]
                });
                if (user)
                    ctx.user = user.toJSON();
            }
        }
        ctx.setJwt = (name, data, options) => {
            ctx.cookies.set(name, jwt.sign(data, ctx.app.config.jwtKey), options);
        };
        ctx.getJwt = name => {
            return jwt.verify(ctx.cookies.get(name), ctx.app.config.jwtKey);
        };
        await next();
    };
};